package my.android.call;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;

/**
 * Created by dinhthao on 6/29/13.
 */
public class ReceiverOutGoingCall extends BroadcastReceiver {

    private  static long timeStart = -1L;
    private static long timeEnd;
    private static String phoneNumber;
    private Context con;
    @Override
    public void onReceive(Context context, Intent intent) {
        con = context;
        phoneNumber =  intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        Toast.makeText(context,"calling " + phoneNumber, Toast.LENGTH_LONG).show();
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        MyPhoneStateListener phoneStateListener = new MyPhoneStateListener();
        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

    }

    private class MyPhoneStateListener extends PhoneStateListener{
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            //start call
            if(state == TelephonyManager.CALL_STATE_OFFHOOK){
                timeStart = System.currentTimeMillis();
                Toast.makeText(con, "start...", Toast.LENGTH_SHORT).show();
                return;

            }

            //end call
           if(state == TelephonyManager.CALL_STATE_IDLE && timeStart != -1L){
               timeEnd = System.currentTimeMillis();
               Toast.makeText(con, "end...", Toast.LENGTH_SHORT).show();
               timeStart = -1;

            }
        }
    }
}
